//
//  todayTopicViewController.m
//  Cup
//
//  Created by dllo on 15/4/24.
//  Copyright (c) 2015年 doll. All rights reserved.
//

#import "todayTopicViewController.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "CommentModel.h"
#import "todayDetailModel.h"
#import "User.h"
#import "todayTopicCell.h"
#import "shareinfo.h"
#import "UMSocial.h"
#import "dataBaseHandle.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface todayTopicViewController ()<UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *topicCommentArr; // 把解析后的评论数据都加到这个数组里
@property(nonatomic, assign)NSInteger page; // 当前的页数,作为post解析的时候body里的一个参数
@property(nonatomic, copy)NSString *commentTotalNumber; // 总共的评论数,用来判断当前页面的内容是否已全部加载
@property(nonatomic, retain)todayDetailModel *topic; // 创建一个model,作为一个容器装tableview的headview里需要的数据
@property(nonatomic,retain)shareinfo *shareinfo; // 保存分享的时候所需要的数据
@end

@implementation todayTopicViewController

// 初始化方法
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.topicCommentArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = YES;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, self.view.frame.size.height - 20) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView.legendFooter beginRefreshing];
    [self dataStartAnalysis];
    self.page = 0;
    [self addContentDataAnalysis];
    [self method];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fenxiang.png"] style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:59/255.0 green:54/255.0 blue:24/255.0 alpha:1];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(turnBack)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:59/255.0 green:54/255.0 blue:24/255.0 alpha:1];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Top" forState:UIControlStateNormal];
    button.frame = CGRectMake(0.8 * WIDTH, 0.74 * HEIGHT, 36, 36);
    button.layer.borderWidth = 1;
    button.backgroundColor = [UIColor blackColor];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.clipsToBounds = YES;
    button.alpha = 0.8;
    button.layer.cornerRadius = 18;
    [button addTarget:self action:@selector(moveToTop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    // Do any additional setup after loading the view.
}

- (void)moveToTop
{
    self.tableView.contentOffset = CGPointMake(0, 0);
}

- (void)turnBack
{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)share
{
    NSString *str = self.shareinfo.pic;
    UIImage *shareImage = [UIImage imageNamed:str];
    NSString *shareText = self.shareinfo.text;
    NSString *shareURL = self.shareinfo.url;
    NSString *share = [NSString stringWithFormat:@"%@   %@",shareText,shareURL];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"553afad967e58e7cba0031e4" shareText:share  shareImage:shareImage shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQQ, nil] delegate:self];
}

- (void)dataStartAnalysis   // headView数据解析
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.idNum,@"contentid",@"1",@"client",@"C6972C4A-C6C9-44C4-B88D-C33304867ED8",@"deviceid",@"",@"auth",@"3.0.0",@"version", nil];
    [manager POST:@"http://api2.pianke.me/group/posts_info"parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *startDic = (NSMutableDictionary *)responseObject;
        NSMutableDictionary *dataDic = [startDic objectForKey:@"data"];
        NSMutableDictionary *postsinfoDic = [dataDic objectForKey:@"postsinfo"];
        NSMutableDictionary *shareinfoDic = [postsinfoDic objectForKey:@"shareinfo"];
        self.shareinfo = [[shareinfo alloc] init];
        [self.shareinfo setValuesForKeysWithDictionary:shareinfoDic];
        [self.shareinfo release];
        
        NSNumber *number = [dataDic objectForKey:@"commenttotal"];
        self.commentTotalNumber = [NSString stringWithFormat:@"%@",number];
        NSLog(@"%@",self.commentTotalNumber);
        
        self.topic = [[todayDetailModel alloc] init];
        [self.topic setValuesForKeysWithDictionary:postsinfoDic];
        [self.topic release];
        [self tableviewHeaderView];
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)addContentDataAnalysis  // 评论数据的解析方法
{
    if ([dataBaseHandle shareDB].state == 1) {
        NSString *i = [NSString stringWithFormat:@"%ld",self.page * 10];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *dicParam = [NSDictionary dictionaryWithObjectsAndKeys:@"C6972C4A-C6C9-44C4-B88D-C33304867ED8",@"deviceid",@"1",@"client",@"asc",@"sort",@"10",@"limit",@"3.0.0",@"version",self.idNum,@"contentid",i,@"start",@"",@"auth", nil];
        [manager POST:@"http://api2.pianke.me/group/posts_comment" parameters:dicParam success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSInteger number = self.topicCommentArr.count;
            NSString *commentNumber = [NSString stringWithFormat:@"%ld",number];
            if ([self.commentTotalNumber isEqual:commentNumber]) {
                [self.tableView.footer noticeNoMoreData];
            }else{
                NSDictionary *dic = (NSDictionary *)responseObject;
                NSMutableDictionary *commentDic = [dic objectForKey:@"data"];
                NSMutableArray *commentList = [commentDic objectForKey:@"list"];
                
                for (NSMutableDictionary *temp in commentList) {
                    CommentModel *topicComment = [[CommentModel alloc]init];
                    [topicComment setValuesForKeysWithDictionary:temp];
                    [self.topicCommentArr addObject:topicComment];
                    [topicComment release];
                }
                self.page++;
                [self.tableView reloadData];
                [self.tableView.footer endRefreshing];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前无网络，请检查网络后重新尝试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

- (void)method // 上拉加载
{
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [self addContentDataAnalysis];
        [self.tableView reloadData];
    }];
}

#pragma mark tableViewHeaderView部分
- (void)tableviewHeaderView
{
        UILabel *fromLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 25, WIDTH - 60, 15)];
        NSMutableDictionary *groupInfoDic = self.topic.groupInfo;
        NSString *groupInfoString = [groupInfoDic objectForKey:@"title"];
        fromLabel.text = [NSString stringWithFormat:@"from : %@",groupInfoString];
        fromLabel.font = [UIFont systemFontOfSize:13];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = self.topic.title;
        titleLabel.numberOfLines = 0;
        [titleLabel sizeToFit];
        titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Helvetica-Bold" size:20],NSFontAttributeName, nil];
        CGRect rect = [titleLabel.text boundingRectWithSize:CGSizeMake(WIDTH - 60, 200) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        titleLabel.frame = CGRectMake(30, 50, WIDTH - 60, rect.size.height);
        
        User *user = [[User alloc] init];
        NSMutableDictionary *userDic = self.topic.userinfo;
        [user setValuesForKeysWithDictionary:userDic];
        
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(125, 91 + rect.size.height, 0.48 * WIDTH, 35)];
        if ([user.uname isEqualToString:@"片刻"]) {
            nameLabel.text = @"三人行";
            nameLabel.font = [UIFont systemFontOfSize:14];
        }else{
            nameLabel.text = user.uname;
            nameLabel.font = [UIFont systemFontOfSize:14];
        }
        
        UILabel *landlordLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 100 + rect.size.height, 20, 15)];
        landlordLabel.text = @"楼主";
        landlordLabel.textColor = [UIColor brownColor];
        landlordLabel.textAlignment = NSTextAlignmentCenter;
        landlordLabel.layer.borderWidth = 1;
        landlordLabel.font = [UIFont systemFontOfSize:8];
        
        UIImageView *userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(45, 85 + rect.size.height, 40, 40)];
        userImageView.clipsToBounds = YES;
        userImageView.layer.cornerRadius = 20;
        NSURL *userImageURL = [NSURL URLWithString:user.icon];
        [userImageView sd_setImageWithURL:userImageURL placeholderImage:[UIImage imageNamed:@"touxiangzhanweitu"  ]];
        
        UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.65 * WIDTH, 120 + rect.size.height, 80, 30)];
        timeLabel.font = [UIFont systemFontOfSize:12];
        timeLabel.text = self.topic.addtime_f;
        
        UIImageView *imageView = [[UIImageView alloc] init];
        NSURL *URL = [NSURL URLWithString:self.coverimgString];
        [imageView sd_setImageWithURL:URL placeholderImage:[UIImage imageNamed:@"zhanwei"]];
        CGFloat picheight = imageView.image.size.height * (self.view.frame.size.width - 60) / (imageView.image.size.width + 0.1);
        imageView.frame = CGRectMake(40, 160 + rect.size.height, WIDTH - 80, picheight);
    
        NSString *htmlString = self.topic.html;
        NSArray *components = [htmlString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
        NSMutableArray *componentsToKeep = [NSMutableArray array];
        for (int i = 0; i < [components count]; i = i + 2) {
            [componentsToKeep addObject:[components objectAtIndex:i]];
        }
        NSString *plainText = [componentsToKeep componentsJoinedByString:@""];
        NSRange range = {116, plainText.length - 140};
        NSString *contentStr = [plainText substringWithRange:range];
        
        UILabel *contentLabel = [[UILabel alloc] init];
        contentLabel.text = contentStr;
        contentLabel.numberOfLines = 0;
        [contentLabel sizeToFit];
        contentLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
        NSDictionary *dicContent = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Helvetica-Bold" size:16],NSFontAttributeName, nil];
        contentLabel.textColor = [UIColor brownColor];
        CGRect rectContent = [contentLabel.text boundingRectWithSize:CGSizeMake(WIDTH - 60, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dicContent context:nil];
        contentLabel.frame = CGRectMake(30, 175 + rect.size.height + picheight, WIDTH - 60, rectContent.size.height);
        
        self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200 + rect.size.height + rectContent.size.height + picheight)];
        [self.tableView.tableHeaderView addSubview:fromLabel];
        [fromLabel release];
        [self.tableView.tableHeaderView addSubview:titleLabel];
        [titleLabel release];
        [self.tableView.tableHeaderView addSubview:nameLabel];
        [nameLabel release];
        [self.tableView.tableHeaderView addSubview:landlordLabel];
        [landlordLabel release];
        [self.tableView.tableHeaderView addSubview:userImageView];
        [userImageView release];
        [self.tableView.tableHeaderView addSubview:timeLabel];
        [timeLabel release];
        [self.tableView.tableHeaderView addSubview:imageView];
        [imageView release];
        [self.tableView.tableHeaderView addSubview:contentLabel];
        [contentLabel release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentModel *comment = self.topicCommentArr[indexPath.row];
    NSDictionary *dicContent = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12],NSFontAttributeName, nil];
    CGRect rectContent = [comment.content boundingRectWithSize:CGSizeMake(WIDTH - 60, 400) options:NSStringDrawingUsesLineFragmentOrigin attributes:dicContent context:nil];
    return 110 + rectContent.size.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topicCommentArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    todayTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[todayTopicCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
    }
    CommentModel *comment = self.topicCommentArr[indexPath.row];
    NSString *timeString = comment.addtime_f;
    NSMutableDictionary *userinfoDic = comment.userinfo;
    User *usr = [[User alloc] init];
    [usr setValuesForKeysWithDictionary:userinfoDic];
    NSURL *URL = [NSURL URLWithString:usr.icon];
    [cell.userImageView sd_setImageWithURL:URL placeholderImage:[UIImage imageNamed:@"touxiangzhanweitu"]];
    cell.nameLabel.text = usr.uname;
    NSInteger number = indexPath.row + 2;
    cell.timeLabel.text = [NSString stringWithFormat:@"%ld楼 · %@",number,timeString];
    cell.contentLabel.text = comment.content;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)dealloc
{
    [_tableView release];
    [_topic release];
    [_topicCommentArr release];
    [_shareinfo release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
